<template>
    <el-row :gutter="20">
        <el-col :span="13" :offset="0" style="background-color: rgb(83, 135, 193);">
            <div class="div">
                <img src="@/assets/svgs/login-box-bg.svg" alt="bg">
            </div>
        </el-col>
        <el-col :span="11" :offset="0">
            <div class="div">
                <div style="width:100%;text-align:center;margin-bottom: 20px;">
                    <el-radio-group v-model="loginUser" @change="loginUserChange" fill="#409eff">

                        <el-radio-button label="租户登录" value="tenant" size="large" />

                        <el-radio-button label="员工登录" value="emp" size="large" />
                    </el-radio-group>
                </div>
                <el-form ref="ruleFormRef" :model="loginForm" :rules="LoginRules" label-position="right"
                    class="demo-ruleForm" label-width="auto" size="large">
                    <el-form-item>
                        <el-divider content-position="center"> <span style="font-weight: 800;font-size: 20pt">
                                {{ loginUserFormat }}</span></el-divider>
                    </el-form-item>

                    <el-form-item align="left" label="用户名：" prop="uName">
                        <el-input v-model="loginForm.uName" />
                    </el-form-item>

                    <!--密码-->

                    <el-form-item align="left" label="密码：" prop="uPwd">
                        <el-input v-model="loginForm.uPwd" show-password />
                    </el-form-item>
                    <!--验证码-->
                    <el-form-item label="验证码：" prop="verifyCode">
                        <el-row :gutter="20" style="width:100%">
                            <el-col :span="14" :offset="0">
                                <el-input v-model="loginForm.verifyCode" />
                            </el-col>

                            <el-col :span="10" :offset="0">
                                <img :src="generateCode" @click="freshVerifyCode">
                            </el-col>
                        </el-row>
                    </el-form-item>
                    <!--选择门店-->
                    <el-form-item v-show="loginUser == 'emp'" label="选择门店：">
                        <el-select v-model="loginForm.storeId" class="m-2" size="default" placeholder="请选择门店" clearable
                            filterable>
                            <el-option v-for="item in storeList.values" :key="item.StoreId" :label="item.StoreName"
                                :value="item.StoreId">
                            </el-option>
                        </el-select>

                    </el-form-item>
                    <!--记住密码-->
                    <el-row :gutter="20">
                        <el-col :span="12" :offset="0">
                            <el-form-item label="    ">
                                <el-checkbox v-model="loginForm.isRemember">记住密码</el-checkbox>
                            </el-form-item>


                        </el-col>
                        <el-col :span="12" :offset="0">
                            <el-form-item style="float:right">

                                <el-link type="primary">
                                    忘记密码？</el-link>
                                <el-link type="primary" v-show="loginUser != 'emp'"
                                    @click="router.push('/tenantRegister')">
                                    去注册</el-link>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <!--登录按钮 -->
                    <el-form-item label="    ">
                        <el-button type="primary" size="default" @click="userLogin(ruleFormRef)">
                            登录 </el-button>

                    </el-form-item>

                    <el-col :span="24" style="padding-right: 10px; padding-left: 10px">
                        <!--登录方式 -->
                        <el-form-item label="    ">
                            <el-row :gutter="5" justify="space-between" style="width: 100%">
                                <el-col :span="8">
                                    <el-button type="default" size="default">
                                        手机登录
                                    </el-button>

                                </el-col>
                                <el-col :span="8">
                                    <el-button type="default" size="default">
                                        二维码登录
                                    </el-button>
                                </el-col>
                                <el-col :span="8">
                                    <el-button type="default" size="default">
                                        注册
                                    </el-button>
                                </el-col>
                            </el-row>
                        </el-form-item>
                    </el-col>

                    <!--其他登录方式 -->
                    <el-divider content-position="center">
                        其他登录方式
                    </el-divider>
                    <el-col :span="24" style="padding-right: 10px; padding-left: 10px">
                        <el-form-item>
                            <div style="margin:0 auto">
                                <Icon v-for="(item, key) in socialList" :key="key" :icon="item.icon" :size="30"
                                    color="#999" style="margin-right:50px;width:30px;height:30px;" />
                            </div>
                        </el-form-item>
                    </el-col>


                    <el-divider content-position="center">
                        萌新必读
                    </el-divider>
                    <el-col :span="24">
                        <el-form-item>
                            <div style="margin:0 auto">
                                <el-link href="https://doc.iocoder.cn/" target="_blank">📚开发指南
                                </el-link>
                                <el-link href="https://doc.iocoder.cn/video/" target="_blank">
                                    🔥视频教程
                                </el-link>
                                <el-link href="https://www.iocoder.cn/Interview/good-collection/" target="_blank">
                                    ⚡面试手册
                                </el-link>
                                <el-link href="http://static.yudao.iocoder.cn/mp/Aix9975.jpeg" target="_blank">
                                    🤝外包咨询
                                </el-link>
                            </div>
                        </el-form-item>
                    </el-col>
                </el-form>
            </div>
        </el-col>
    </el-row>
</template>

<script setup lang="ts">
import { ElMessage } from 'element-plus';
import { reactive, ref } from 'vue'
import { onMounted } from 'vue'
import { local, session } from "@/stores/storageHelper"
import { useRoute } from "vue-router"
import type { FormInstance, FormRules } from 'element-plus'
import { Icon } from '@iconify/vue';
import router from '@/router';
import { loginStore } from "@/stores/login";
import type { IUser } from '@/stores/login';
import axios from 'axios';
import { baseURL_dev } from '@/config/baseURL'
import { baseURL_captcha } from '@/config/baseURL'
const baseURL = baseURL_dev
import { ConsoleSqlOutlined } from '@ant-design/icons';
axios.defaults.baseURL = baseURL;
const captcha = baseURL_captcha


const Route = useRoute();

var store = loginStore();




const loginForm = reactive({
    uName: "",
    uPwd: "",
    verifyCode: "",
    isRemember: false,
    storeId: "",
})
const LoginRules = reactive({
    uName: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '长度在 3 到 10 个字符', trigger: 'blur' }
    ],
    uPwd: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { pattern: "^[a-zA-Z0-9_.]+$", message: '只能输入字母数字_.', trigger: 'blur' }
    ],
    verifyCode: [
        { required: true, message: '请输入验证码', trigger: 'blur' },

    ]
})
//其他登录方式
const socialList = [
    { icon: 'ant-design:wechat-filled', type: 30 },
    { icon: 'ant-design:dingtalk-circle-filled', type: 20 },
    { icon: 'ant-design:github-filled', type: 0 },
    { icon: 'ant-design:alipay-circle-filled', type: 0 }
]
//验证码
const generateCode = ref('')
//随机数
const randomNum = ref(0)
const freshVerifyCode = () => {
    randomNum.value = Number(Math.floor(Math.random() * 10))
    generateCode.value = captcha + `captcha?id=${randomNum.value}`
    console.log(randomNum.value)
}
//选择门店
const storeList = reactive([{
    StoreId: "",
    StoreName: "",
}])
//获取门店列表
function getStoreList() {
    axios.get('Store/GetStoreList').then(res => {
        storeList.values = res.data.Data;
        console.log(storeList.values)
    })
}


//登录用户
const loginUser = ref('emp')
const loginUserFormat = ref('员工登录')
function loginUserChange() {
    if (loginUser.value == 'emp') {
        loginUserFormat.value = '员工登录'
    } else {
        loginUserFormat.value = '租户登录'
    }
}
const ruleFormRef = ref<FormInstance>()
//登录
async function userLogin(formEl: FormInstance | undefined) {
    if (!formEl) return;
    formEl.validate(async (valid, fields) => {
        if (valid) {
            let isVerifyPassed = ref(false);
            //获取验证码
            await axios.get(captcha + "captcha/validate", {
                params: {
                    id: randomNum.value.toString(),
                    code: loginForm.verifyCode
                }
            }).then(res => {
                if (!res.data) {
                    ElMessage.error('验证码错误');
                    //verifyPassed = false;
                }
                else {
                    isVerifyPassed.value = true;
                }
            }
            );

            if (!isVerifyPassed.value) {
                return;
            }
            //登录
            let url = ref('');
            if (loginUser.value == 'emp') {
                url.value = 'Employee/EmpLogin';
            }
            else {
                //租户登录
                url.value = 'User/UserLogin';
            }
            //alert(url);
            await axios.post(url.value, {
                uName: loginForm.uName,
                uPwd: loginForm.uPwd,
                storeId: loginForm.storeId,
            }).then(res => {
                {
                    if (res.data.Code == 200) {
                        ElMessage.success('登录成功');
                        //判断是否记住密码
                        if (loginForm.isRemember) {
                            //记住账号密码
                            local.set("uName", loginForm.uName);
                            local.set("uPwd", loginForm.uPwd);
                            let user = ref<IUser>({
                                UName: res.data.Data.UName,
                                Token: res.data.Data.Token,
                                UId: res.data.Data.UId,
                                StoreId: loginForm.storeId,
                                TenantId: res.data.Data.TenantId,
                                IsTenant: res.data.Data.IsTenant,
                            });
                            //记住token                           
                            store.setUserInfo(user.value);
                            console.log(store.getUserInfo());
                            //存储请求头
                            axios.defaults.headers.common['Authorization'] = 'Bearer ' + res.data.Data.Token;
                            session.set("token", res.data.Data.Token);
                        }
                        //判断是否是租户
                        session.set("isTenant", res.data.Data.IsTenant);
                        //导航守卫
                        store.setIsLogin(true);

                        //跳转
                        router.push('/');
                    }
                    else {
                        ElMessage.error(res.data.Msg);
                        freshVerifyCode();
                    }
                }
            })
        }
        else {
            console.log('error submit!')
        }
    })

}

onMounted(() => {
    freshVerifyCode();
    //记住密码
    if (local.get('uName')) {
        loginForm.uName = local.get('uName') ?? "";
        loginForm.uPwd = local.get('uPwd') ?? "";
        loginForm.isRemember = true;
    }
    getStoreList();
})


</script>

<style scoped>
.div {
    float: left;
    width: 100%;
}

.el-form {
    width: 80%;
    margin: 0 auto;
}

img {
    width: 100%;
    height: 100%;
    margin: 0 auto
}

.el-link {
    margin-right: 20px;
}

.el-button {
    width: 100%
}
</style>